package com.wecode.core.utils;

import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;

/**
 * Created by youngwa on 2018/12/05 22:33
 */
public class ClassUtils {

    public static Field[] getFileds(Class<?> clzz) {
        if (clzz == null) {
            throw new IllegalArgumentException("clzz is not allow null");
        }
        Field[] fields = new Field[0];
        do {
            Field[] fs = clzz.getDeclaredFields();
            Field[] tempfs = new Field[fields.length + fs.length];
            System.arraycopy(fields, 0, tempfs, 0, fields.length);
            System.arraycopy(fs, 0, tempfs, fields.length, fs.length);
            fields = tempfs;
        } while ((clzz = clzz.getSuperclass()) != Object.class);
        return fields;
    }

    public static Field getField(Class<?> clzz, String fieldName) {
        if (clzz == null) {
            throw new IllegalArgumentException("clzz is not allowed null");
        }
        if (StringUtils.isBlank(fieldName)) {
            throw new IllegalArgumentException("fieldName is not allowed null");
        }
        do {
            Field[] fs = clzz.getDeclaredFields();
            for (Field f : fs) {
                if (f.getName().equals(fieldName)) {
                    return f;
                }
            }

        } while ((clzz = clzz.getSuperclass()) != Object.class);
        return null;
    }
}
